/*
 * @Date: 2024-07-12 11:53:34
 * @LastEditors: 陈俊宇 467724386@qq.com
 * @LastEditTime: 2024-07-31 16:41:00
 */
// 创建Vue.js的script标签
const vueScript = document.createElement('script')
vueScript.src = 'https://unpkg.com/vue@3.4.33/dist/vue.global.prod.js'
vueScript.defer = true // 添加defer属性
document.head.appendChild(vueScript)

// 创建你的组件库的script标签
const myComponentScript = document.createElement('script')
// myComponentScript.src = './dist/service-chat.js'
// myComponentScript.src = 'http://120.78.176.115/service-chat.js'
myComponentScript.src =
    'https://static-resource-witek.s3.us-east-2.amazonaws.com/public/js/service-chat.js'
myComponentScript.defer = true // 添加defer属性

// 添加一个回调函数，确保两个脚本都加载完成后再执行
let vueLoaded = false
let componentLoaded = false

vueScript.onload = () => {
    document.head.appendChild(myComponentScript)
}

myComponentScript.onload = () => {
    initServiceChat()
}

async function initServiceChat() {
    const { createApp, h, render } = Vue

    const appContainer = document.createElement('div')
    appContainer.id = 'chat-app'
    document.body.appendChild(appContainer)

    const app = createApp({})
    app.use(ServiceChat)
    app.mount('#chat-app')

    // 在Vue实例中控制组件显示的变量
    app.config.globalProperties.showServiceChat = false

    // 定义一个方法来动态创建并挂载ServiceChat组件
    app.config.globalProperties.toggleServiceChat = function (params) {
        if (this.showServiceChat) {
            this.showServiceChat = false
            return
        }

        const ServiceChatComponent = app.component('ServiceChat')

        // 创建组件的虚拟节点并传递参数
        const serviceChatVNode = h(ServiceChatComponent, {
            // 这里传递参数，例如：
            message: params.message,
            user: params.user,
            // 根据需要添加更多参数
        })

        const container = document.createElement('div')
        document.getElementById('chat-app').appendChild(container)

        render(serviceChatVNode, container)

        this.showServiceChat = true
    }

    // 调用方法以显示组件并传递参数
    app.config.globalProperties.toggleServiceChat({
        message: 'Hello from the caller!',
        user: 'User123',
    })
}
